﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace Application.Service
{
    public class MenuService : IMenuService
    {
        private IConfiguration _config { get; set; }
        private List<SysRole> _sysRoleOptions { get; set; }
        private readonly Accessor _accessor;
        public MenuService(IConfiguration config, IOptions<List<SysRole>> sysRoleOptions, Accessor accessor)
        {
            _config = config;
            _sysRoleOptions = sysRoleOptions.Value;
            _accessor = accessor;
        }

        public Task<List<RouteInfo>> GetMenuListByRoleKey()
        {
            var menus = GetAllMenu();
            if (_accessor.RoleKey != GlobalData.Role.SupperAdminRoleKey)//非超级管理员
            {
                var menuIds = _sysRoleOptions.FirstOrDefault(s => s.Key == _accessor.RoleKey)?.MenuIds;
                menus = menus.Where(s => menuIds.Contains(s.Id));
            }

            var existParentMenu = (SysMenu sysMenu) => { return menus.Any(f => f.Type == MenuType.menu && f.Id == sysMenu.ParentId); };

            var listRoute = menus.Select(s => new RouteInfo
            {
                Name = s.RoutePath,
                Path = !existParentMenu(s) ? "/" + s.RoutePath : s.RoutePath,
                ParentId = s.ParentId,
                Id = s.Id,
                Component = s.ComponentPath,
                Type = s.Type,
                Hidden = s.Hidden,
                Meta = new RouteInfo.MetaInfo
                {
                    Title = s.Title,
                    Icon = s.Icon,
                }
            }).ToList();
            return Task.FromResult(listRoute);
        }

        public IEnumerable<SysMenu> GetAllMenu()
        {
            var datas = (List<SysMenu>)_config.GetSection("Menus").Get(typeof(List<SysMenu>));
            var result = ConvertTreeToList(datas);
            return result;
        }
        private static List<SysMenu> ConvertTreeToList(List<SysMenu> roots)
        {
            List<SysMenu> result = new List<SysMenu>();
            foreach (var root in roots)
            {
                ConvertTreeToListRecursive(root, null, result);
            }
            return result;
        }

        private static void ConvertTreeToListRecursive(SysMenu node, int? parentId, List<SysMenu> result)
        {
            node.ParentId = Convert.ToInt32(parentId); // 设置父节点的Id

            result.Add(node); // 将当前节点添加到结果列表

            if (node.Children != null && node.Children.Count > 0)
            {
                foreach (var childNode in node.Children)
                {
                    ConvertTreeToListRecursive(childNode, node.Id, result); // 递归处理子节点
                }
            }
        }
    }
    public interface IMenuService
    {
        Task<List<RouteInfo>> GetMenuListByRoleKey();
        IEnumerable<SysMenu> GetAllMenu();
    }
}
